package com.example.helloworld

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import java.text.SimpleDateFormat
import java.util.*

class ClockFragment : Fragment() {
    private lateinit var dateText: TextView
    private lateinit var weekText: TextView
    private lateinit var beijingTimeText: TextView
    private lateinit var usaTimeText: TextView
    private val handler = Handler(Looper.getMainLooper())
    private val updateTimeRunnable = object : Runnable {
        override fun run() {
            updateTime()
            handler.postDelayed(this, 100)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_clock, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dateText = view.findViewById(R.id.dateText)
        weekText = view.findViewById(R.id.weekText)
        beijingTimeText = view.findViewById(R.id.beijingTimeText)
        usaTimeText = view.findViewById(R.id.usaTimeText)
        
        handler.post(updateTimeRunnable)
    }

    private fun updateTime() {
        val calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"))
        val date = calendar.time

        // 更新日期
        val dateFormat = SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA)
        dateText.text = dateFormat.format(date)

        // 更新星期
        val weekFormat = SimpleDateFormat("EEEE", Locale.CHINA)
        weekText.text = weekFormat.format(date)

        // 更新北京时间
        val beijingTime = SimpleDateFormat("HH:mm:ss", Locale.CHINA).format(date)
        beijingTimeText.text = "北京时间：$beijingTime.${String.format("%01d", calendar.get(Calendar.MILLISECOND) / 100)}0"

        // 更新美国时间
        val usaCalendar = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"))
        val usaTimeFormat = SimpleDateFormat("HH:mm:ss", Locale.US)
        usaTimeFormat.timeZone = TimeZone.getTimeZone("America/New_York")
        val usaTime = usaTimeFormat.format(usaCalendar.time)
        usaTimeText.text = "美国时间：$usaTime.${String.format("%01d", usaCalendar.get(Calendar.MILLISECOND) / 100)}0"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        handler.removeCallbacks(updateTimeRunnable)
    }
} 